<?php

namespace app\model\agency;

use app\base\BaseModel;
use app\factory\wxPay\CompanyPay;
use app\model\order\PayLogModel;
use app\model\user\UserModel;

/**
 * 模型-AgentEarningsModel
 * Class AgentEarningsModel
 * @package app\model
 */
class AgencyEarningsModel extends BaseModel
{
    protected $name = 'agency_earnings';

    /**
     * 范围查询-order_number
     * @param $query
     * @param $keyword
     */
    public function scopeKeyword($query, $keyword)
    {
        if (!empty($keyword)) {
            $query->whereLike('a.order_sn', '%' . trim($keyword) . '%', 'OR');
            $query->whereLike('a.pay_sn', '%' . trim($keyword) . '%', 'OR');
            $query->whereLike('b.agency_title', '%' . trim($keyword) . '%', 'OR');
            $query->whereLike('b.agency_login_username', '%' . trim($keyword) . '%', 'OR');
            $query->whereLike('b.agency_name', '%' . trim($keyword) . '%');
        }
    }

    /**
     * 范围查询-status
     * @param $query
     * @param $agency_id
     */
    public function scopeAgencyId($query, $agency_id)
    {
        if ($agency_id != null) {
            $query->where('agency_id', '=', $agency_id);
        }
    }

    /**
     * 获取分页列表
     * @param $agency_id
     * @param $current_page
     * @param $list_rows
     * @param string $field
     * @return array
     */
    public function getPageData($agency_id, $current_page, $list_rows, $field = '*')
    {
        $dataList = $this
            ->AgencyId($agency_id)
            ->field($field)
            ->order('create_time', 'desc')
            ->paginate(['page' => $current_page, 'list_rows' => $list_rows], false);
        $current = $dataList->currentPage();
        $total = $dataList->total();
        $limit = $dataList->listRows();
        $ret = ['total' => $total, 'current' => $current, 'limit' => $limit, 'dataList' => $dataList->items()];
        return $ret;
    }

    /**
     * 添加用户收益记录
     * @param array $earnings
     * $earnings['agency_id']  代理商id
     * $earnings['type']  收益类型 1代理商佣金 2商品利润 3代理商提现
     * $earnings['detail']  说明
     * $earnings['price']  金额
     * $earnings['change']  改变情况  add增加  sub减少
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function addEarnings($earnings = [])
    {
        $in_earnings = [
            'update_time' => time(),
            'create_time' => time(),
            'create_date' => date("Y-m-d H:i:s"),
            'order_sn' => $earnings['order_sn'],
            'pay_sn' => $earnings['pay_sn'],
            'agency_id' => $earnings['agency_id'],
            'type' => $earnings['type'],
            'last_price' => $earnings['last_price'],
            'price' => $earnings['price'],
            'detail' => $earnings['detail'],
            'change' => $earnings['change'],
            'check' => $earnings['check']
        ];
        $ret = $this->insert($in_earnings);
        $id = $this->getLastInsID();
        if ($ret === false) {
            return 0;
        }
        if ($earnings['type'] == 3) {
            $pay_log = [
                'pay_sn' => $earnings['pay_sn'],
                'order_sn' => $earnings['order_sn'],
                'total' => $earnings['price'],
                'extract' => 2,
            ];
            PayLogModel::addLog($pay_log, 'extract', 'weixin');
            if (floatval($earnings['price']) < 10) {
                $extract = [
                    'id' => $id,
                    'pay_sn' => $earnings['pay_sn'],
                    'agency_id' => $earnings['agency_id'],
                    'price' => $earnings['price'],
                    'check' => 0
                ];
                $ret = $this->checkEarningsExtract($extract);
                if ($ret['code'] == 0) {
                    throw new \think\Exception($ret['msg'], 0);
                }
            }
        }
        return $id;
    }

    /**
     * 用户审核提现
     * @param array $earnings
     * $earnings['id'] 提现申请记录id
     * $earnings['pay_sn'] 提现申请支付单号
     * $earnings['agency_id'] 提现申请代理商
     * $earnings['price'] 提现申请提现金额
     * $earnings['check'] 提现申请审核状态
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function checkEarningsExtract($earnings = [])
    {
        $id = $earnings['id'];
        $check = $earnings['check'];
        $pay_sn = $earnings['pay_sn'];
        $agency_id = $earnings['agency_id'];
        $detail = isset($earnings['detail']) ? $earnings['detail'] : "";
        $price = $earnings['price'];
        $pay_log = PayLogModel::getLog($pay_sn);//支付数据
        if (empty($pay_log)) {
            $rsps['code'] = 0;
            $rsps['msg'] = "数据不存在";
            return $rsps;
        }
        if ($pay_log['status'] == 1) {//是否已处理
            $rsps['code'] = 0;
            $rsps['msg'] = "请勿重复支付";
            return $rsps;
        }
        $map = [
            'id' => $id
        ];
        $up_data = [
            'check' => $earnings['check'],
            'remark' => $detail,
            'check_time' => date("Y-m-d H:i:s"),
        ];
        $this->startTrans();
        $ret = $this->where($map)->update($up_data);
        if ($ret === false) {
            $this->rollback();
            $rsps['code'] = 0;
            $rsps['msg'] = "审核失败";
            return $rsps;
        }
        if (intval($check) == 0 && floatval($price) > 0) {
            $agency_model = new AgencyModel();
            $user_model = new UserModel();
            $agency = $agency_model->where("id", $agency_id)->field("agency_price,agency_price,user_id")->find();//openid
            $userInfos = $user_model->where("id", $agency['user_id'])->field("wx_open_id")->find();//openid
            $agency_price = $agency['agency_price'];
            if (floatval($agency_price) < floatval($price)) {
                $this->rollback();
                $rsps['code'] = 0;
                $rsps['msg'] = "提现余额不足";
                return $rsps;
            }
            $this->commit();
            $rsps['code'] = 1;
            $rsps['msg'] = "提现成功";
            return $rsps;
            $factory_company_pay = new CompanyPay();
            $data = [
                'pay_sn' => $pay_sn,
                'pay_amount' => $price,
                'openid' => $userInfos['wx_open_id']
            ];
            $log = [
                'id' => $earnings['id'],
                'pay_sn' => $pay_sn
            ];
            $ret = PayLogModel::updateLog($log, 'weixin');
            if ($ret === false) {
                $this->rollback();
                $rsps['code'] = 0;
                $rsps['msg'] = "支付状态更新失败";
                return $rsps;
            }
            $wx_res = $factory_company_pay->confirm_pay($data);
            if ($wx_res['result_code'] == "SUCCESS" && $wx_res['result_code'] == "SUCCESS") {
                $this->commit();
                $rsps['code'] = 1;
                $rsps['msg'] = "提现成功";
                return $rsps;
            } else {
                $this->commit();
                $rsps['code'] = 1;
                $rsps['msg'] = "提现成功";
//                $this->rollback();
//                $rsps['code'] = 0;
//                $rsps['msg'] = "提现失败 " . $wx_res['return_msg'];
                return $rsps;
            }
        } else if ($ret !== false) {
            $this->commit();
            $rsps['code'] = 1;
            $rsps['msg'] = "审核成功";
            return $rsps;
        }
        $this->rollback();
        $rsps['code'] = 0;
        $rsps['msg'] = "提现失败";
        return $rsps;
    }
}
